package com.zw.chat.controller;

import com.zw.chat.common.context.MessageContext;
import com.zw.chat.common.domain.AjaxResult;
import com.zw.chat.common.sse.SseSession;
import com.zw.chat.domain.ChatMessage;
import com.zw.chat.service.IChatMessageService;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.style.ValueStyler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.LinkedList;
import java.util.Objects;

/**
 * @author by: zyl
 * @ClassName: ChatMessageController
 * @Description: 聊天消息控制器
 * @Date: 2024/12/5 11:19
 */
@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/chat")
public class ChatMessageController {


    @Autowired
    private IChatMessageService chatMessageService;


    @ResponseBody
    @PostMapping("/sse")
    public AjaxResult createChatEmitter(@RequestBody ChatMessage chatMessage) {
        if (Objects.isNull(chatMessage.getSession())) {
            return AjaxResult.error();
        }
        if (!StringUtils.hasText(chatMessage.getContent())) {
            return AjaxResult.warn("请输入内容");
        }
        LinkedList<Message> message = MessageContext.getMessage(chatMessage.getSession().getId());
        message.add(new UserMessage(chatMessage.getContent()));
        MessageContext.addMessage(chatMessage.getSession().getId(), message);
        SseEmitter emitter = SseSession.getEmitter(chatMessage.getSession().getId());
        SseSession.addEmitter(chatMessage.getSession().getId(), emitter);
        return AjaxResult.success();
    }

    @GetMapping(value = "/message")
    public SseEmitter chatMessage(@RequestParam("sessionId") String sessionId) {
        if (!SseSession.exists(sessionId)) {
            throw new RuntimeException("sse连接不存在");
        }
        chatMessageService.sendMessage(sessionId);
        return SseSession.getEmitter(sessionId);
    }

    @ResponseBody
    @GetMapping(value = "/message/query")
    public AjaxResult queryChatMessage(@RequestParam(value = "sessionId") String sessionId,
                                       @RequestParam("page") Integer page,
                                       @RequestParam("size") Integer size) {
        return AjaxResult.success(chatMessageService.queryChatMessage(sessionId, page, size));
    }

}
